package com.sunnada.wfs.service;

import com.sunnada.wfs.dao.SystemInfoMapper;
import com.sunnada.wfs.utils.JedisPoolClient;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SystemInfoService {

    @Value("${systeminfo.save.key}")
    private String key;

    @Autowired
    private SystemInfoMapper systemInfoMapper;

    public void update(String ip,String value){
        Jedis jedis = JedisPoolClient.getJedis();
        if (jedis!=null) jedis.hset(key,ip,value);
        Map<String,String> map = new HashMap<>();
        map.put("ip",ip);
        map.put("systemInfo",value);
        systemInfoMapper.insert(map);
    }

    public Map<String,String> get(String ip){
        Map<String,String> result = new HashMap<>();
        Jedis jedis = JedisPoolClient.getJedis();
        if (jedis!=null) result = string2Map(ip,jedis.hget(key,ip));
        if (result!=null&&result.size()!=0) return result;
        result = systemInfoMapper.get(ip);
        return result;
    }

    public List<Map<String,String>> getAll(){
        List<Map<String,String>> result = new ArrayList<>();
        Jedis jedis = JedisPoolClient.getJedis();
        if (jedis!=null) result = map2List(jedis.hgetAll(key));
        if (result!=null&&result.size()!=0) return result;
        result = systemInfoMapper.getAll();
        return result;
    }

    private Map<String,String> string2Map(String key,String value){
        Map<String,String> map = new HashMap<>();
        map.put("ip",key);
        map.put("system_info",map.get(value));
        return map;
    }

    private List<Map<String,String>> map2List(Map<String,String> map){
        List<Map<String,String>> list =new ArrayList<>();
        for (String s : map.keySet()) {
            Map<String,String> temp = new HashMap<>();
            temp.put("ip",s);
            temp.put("system_info",map.get(s));
            list.add(temp);
        }
        return list;
    }

}
